package com.irm;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author UncleXiu
 * @version V1.0.0
 * @data 2022-01-20
 */
@Configuration
@MapperScan(value = "com.irm", sqlSessionFactoryRef = "irmDbSessionFactory")
public class IrmDbConf {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${irm.datasource.url}")
    private String irmDbUrl;
    @Value("${irm.datasource.username}")
    private String irmDbUserName;
    @Value("${irm.datasource.password}")
    private String irmDbPassword;
    @Value("${irm.datasource.driverClassName}")
    private String irmDbDriverClass;
    @Value("${irm.mapperLocations}")
    private String irmDbMapper;

    @Bean(name = "irmDbSource")
    public DataSource irmDataSource() {
        logger.info("注册irm数据源");
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(irmDbDriverClass);
        druidDataSource.setUrl(irmDbUrl);
        druidDataSource.setUsername(irmDbUserName);
        druidDataSource.setPassword(irmDbPassword);
        logger.info("数据库连接：{}", irmDbUrl);
        return druidDataSource;
    }

    @Bean(name = "irmDbTransactionManage")
    public DataSourceTransactionManager irmDataSourceTransactionManager(){
        return new DataSourceTransactionManager(irmDataSource());
    }


    @Bean(name = "irmDbSessionFactory")
    public SqlSessionFactory irmDataSourceSessionFactory(@Qualifier("irmDbSource") DataSource masterDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(masterDataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(irmDbMapper));
        return sessionFactoryBean.getObject();
    }

}
